Best time to buy and sell stock

Time: O(N); Space: O(1); easy

Say you have an array for which the i-th element is the price of a given stock on day i.

If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.

Note:

  • You cannot sell a stock before you buy one.

Example 1:

Input: prices = [7,1,5,3,6,4]

Output: 5

Explanation:

  • Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.

  • Not 7-1 = 6, as selling price needs to be larger than buying price.

Example 2:

Input: prices = [7,6,4,3,1]

Output: 0

Explanation:

  • In this case, no transaction is done, i.e. max profit = 0.

Solution

We need to find out the maximum difference (which will be the maximum profit) between two numbers in the given array. Also, the second number (selling price) must be larger than the first one (buying price).

In formal terms, we need to find max(prices[j] - prices[i]), for every i and j such that j > i.

1. Brute Force

[8]:
class Solution1(object):
    """
    Brute Force
    Time: O(n^2). Loop runs (n * (n-1))/2 times.
    Space: O(1). Only two variables are used.
    """
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        max_profit = 0

        for i in range(len(prices) - 1):
            for j in range(i + 1, len(prices)):
                profit = prices[j] - prices[i]
                if profit > max_profit:
                    max_profit = profit
        return max_profit
[9]:
s = Solution1()
prices = [7,1,5,3,6,4]
assert s.maxProfit(prices) == 5
prices = [7,6,4,3,1]
assert s.maxProfit(prices) == 0

2. One Pass

Algorithm Say the given array is: [7, 1, 5, 3, 6, 4] If we plot the numbers of the given array on a graph, we get:

The points of interest are the peaks and valleys in the given graph. We need to find the largest peak following the smallest valley. We can maintain two variables - min_price and max_profit corresponding to the smallest valley and maximum profit (maximum difference between selling price and minprice) obtained so far respectively.

[10]:
class Solution2(object):
    """
    One Pass
    Time: O(n). Only a single pass is needed.
    Space: O(1). Only two variables are used.
    """
    def maxProfit(self, prices):
        '''
        One Pass
        :type prices: List[int]
        :rtype: int
        '''
        max_profit, min_price = 0, float("inf")

        for price in prices:
            min_price = min(min_price, price)
            max_profit = max(max_profit, price - min_price)

        return max_profit
[11]:
s = Solution2()
prices = [7,1,5,3,6,4]
assert s.maxProfit(prices) == 5
prices = [7,6,4,3,1]
assert s.maxProfit(prices) == 0